package com.example.administrator.exkotlin.ui.fragment.news

import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.example.administrator.exkotlin.R
import com.example.administrator.exkotlin.ui.fragment.BaseFragment
import kotlinx.android.synthetic.main.activity_news.*
import kotlinx.android.synthetic.main.news_title_fragment.*

class NewsTitleFragment : BaseFragment() {

    //是否为横屏，控制点击标题之后的事件
    private var isLandView = false

    val newsDatas: MutableList<News> = mutableListOf()

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        Log.i(javaClass.simpleName, "onCreateView")
        return inflater?.inflate(R.layout.news_title_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        isLandView = activity?.findViewById<View>(R.id.fm_content) != null
        initDatas()

    }
    private fun initDatas() {
        for (cout in 0 until 20) {
            Log.i(javaClass.simpleName, "addDatas$cout")
            newsDatas.add(News("$cout", "${System.currentTimeMillis()}"))
        }
        rv_title.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) as androidx.recyclerview.widget.RecyclerView.LayoutManager?
        val adpter = NewsAdapater(newsDatas)
        rv_title.adapter=adpter
        adpter.notifyDataSetChanged()
    }


    inner class NewsAdapater(val newsDatas: List<News>) : androidx.recyclerview.widget.RecyclerView.Adapter<NewsAdapater.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent?.context).inflate(R.layout.new_title__item, parent, false)
            val viewHolder = ViewHolder(view)

            //设置点击事件
            viewHolder.item_view?.setOnClickListener {
                val news = newsDatas[viewHolder.adapterPosition]
                //如果是横屏
                if (isLandView) {
                    val fragment = fm_content as NewsContentFragment
                    fragment.loadNews(news)
                } else {
                    NewsContentActivity.startNewsContentActivity(context, news)
                }
            }
            return viewHolder
        }

        override fun getItemCount(): Int {
            return newsDatas.size
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder?.item_view?.text = newsDatas[position].titel
        }

        inner class ViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
            val item_view = itemView?.findViewById<TextView>(R.id.tv_title)
        }
    }

}